/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    InputLine, Input, TextArea, Text, InputPure, BlobInputList, LineColumn,
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps, useInputControlSure, useItemInputControl
} from "../../common/base";
import {useDeleteAddSub} from "../../hook/useDeleteAddSub";
import '@uppy/core/dist/style.min.css';
import '@uppy/dashboard/dist/style.min.css';
import '@uppy/webcam/dist/style.min.css';
import {useUppyUpload} from "../../hook/useUppyUpload";
import {Each_ZdSetting, useRepTableEditor} from "../../hook/useRepTableEditor";
import {EditStorageContext} from "../../StorageContext";
import {useMeasureInpFilter} from "../../common/hooks";


export const checkConfig部件=[['部件名称'],['部件编号'],['材质'],['规格尺寸'],['坡口型式'],['焊接方法'],['热处理状态','热处理'],
        ['检测部位'],['检测比例'],['检测时机'],['表面状态'],['工件温度'],['检测标准'],['合格级别'],['试块型号'],];
export const PartName=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd,verId,repId}:InternalItemProps,  ref
    ) => {
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
        const getInpFilter = React.useCallback((par: any) => {
            let fields={} as any;
            checkConfig部件.map(([ title,aName], i:number)=> {
                const name =aName? aName : title;
                fields[name] =par[name];
                return null;
            });
            return fields;
        }, []);
        const {line}=useDeleteAddSub(nestMd!, redId!,verId!,repId!);    //同一种分项增加删除操作
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'衍射时差法-部件名称'} >
                {line}
                <br/>
                <LineColumn column={4}>
                {
                    checkConfig部件.map(([title,aName], i:number)=> {
                        const name =aName? aName : title;
                        return <React.Fragment key={i}>
                            <InputLine  label={title+`:`}>
                                <Input  value={inp?.[name] || ''}
                                        onChange={e => {
                                            inp[name] = e.currentTarget.value||undefined;
                                            setInp({...inp});
                                        } } />
                            </InputLine>
                        </React.Fragment>;
                    })
                }
                </LineColumn>
            </InspectRecordLayout>
        );
} );

export const checkConfig仪器=[['仪器型号'],['仪器编号'],['探头型号'],['检测区域'],['焊缝宽度'],['扫查装置'],['检测面'],
    ['耦合剂'],['扫查方式'],['检测面/底面盲区（mm）','盲区1'],['盲区2'],['操作指导书编号','指导书'],];
export const Instrument=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd,verId,repId}:InternalItemProps,  ref
    ) => {
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
        const getInpFilter = React.useCallback((par: any) => {
            let fields={} as any;
            checkConfig仪器.map(([ title,aName], i:number)=> {
                const name =aName? aName : title;
                fields[name] =par[name];
                return null;
            });
            return fields;
        }, []);
        //column={5} breaks={[170,290,390,490,750]}
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'衍射时差法-仪器型号'} column={2}>
                {
                    checkConfig仪器.map(([title,aName], i:number)=> {
                        const name =aName? aName : title;
                        return <React.Fragment key={i}>
                            {i===9?
                                <InputLine  label={title+`:`}>
                                    <div css={{display: 'flex'}}>
                                            <div css={{display: 'flex', flex: '1 1 75%',alignItems: 'baseline'}}>
                                                <InputPure value={inp?.盲区1 ||''}
                                                           onChange={e =>setInp({...inp, 盲区1: e.currentTarget.value} ) } />
                                            </div>
                                            <div css={{display: 'flex', flex: '1 1 25%',alignItems: 'baseline'}}>
                                                <Text variant="h6" css={{wordBreak:'keep-all'}}>/</Text>
                                                <InputPure value={inp?.盲区2 ||''}
                                                           onChange={e =>setInp({...inp, 盲区2: e.currentTarget.value} ) } />
                                            </div>
                                    </div>
                                </InputLine>
                                :
                                i===10? <></>
                                    :
                                    <InputLine  label={title+`:`}>
                                        <Input  value={inp?.[name] || ''}
                                                onChange={e => {
                                                    inp[name] = e.currentTarget.value||undefined;
                                                    setInp({...inp});
                                                } } />
                                    </InputLine>
                            }
                        </React.Fragment>;
                    })
                }
            </InspectRecordLayout>
        );
} );

const cb时窗输入= (inp: any, setInp: React.Dispatch<React.SetStateAction<any>>,name:string) => {
    return  <BlobInputList value={(inp?.[name]) || ''} rows={3}
                           onListChange={v => setInp({ ...inp, [name] :v || undefined}) } />
}
//通道 厚度分区（mm） :? 能不能抽象和复用“通用多行表输入”的组件？  通道表; 二维数组对象表达法。
const config通道表=[['通道','no',52],['厚度分区（mm）','ar',145],['频率（MHz）','hz',115],['晶片尺寸（mm）','ch',145],
    ['楔块角度 （°）','jd',128],['楔块延迟（μs）','la',132],['PCS(mm)','pc',90],['时间窗口设置（μs）','tm',200,cb时窗输入],] as Each_ZdSetting[];
export const Passage=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const breaks=[140,420,620];     //看内容调整: 更紧凑点的
        const headview=<Text variant="h5">
            通道 厚度分区等：
        </Text>;
        const {render}=useRepTableEditor({ref,nestMd,show,alone,redId,
            config: config通道表, table:'通道表', column:3, breaks, label:'衍射时差法-通道 厚度分区', headview
        });
        return  render;
    } );

export const checkConfig灵敏=[['灵敏度设置','灵敏度'],['偏置非平行扫查偏置量（mm）','偏置量'],['偏置扫查次数','偏置扫查'],
            ['偏置非平行扫查底面盲区（mm）','偏置盲区'],['盲区检测'],['横向缺陷检测','横向缺陷'],['检测结果'],];
export const Sensitivity=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd,verId,repId}:InternalItemProps,  ref
    ) => {
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const getInpFilter = React.useCallback((par: any) => {
            let fields={} as any;
            checkConfig灵敏.map(([ title,aName], i:number)=> {
                const name =aName? aName : title;
                fields[name] =par[name];
                return null;
            });
            return fields;
        }, []);
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'光谱-部件名称'} column={0}>
                {
                    checkConfig灵敏.map(([title,aName], i:number)=> {
                        const name =aName? aName : title;
                        return <React.Fragment key={i}>
                            {i===6? <>
                                 检测结果:
                                  <TextArea  value={inp?.检测结果 ||''} rows={4}
                                               onChange={e => setInp({ ...inp, 检测结果: e.currentTarget.value||undefined}) } />
                                  </>
                                :
                                <InputLine  label={title+`:`}>
                                    <Input  value={inp?.[name] || ''}
                                            onChange={e => {
                                                inp[name] = e.currentTarget.value||undefined;
                                                setInp({...inp});
                                            } } />
                                </InputLine>
                            }
                        </React.Fragment>;
                    })
                }
            </InspectRecordLayout>
        );
} );

/** 检 测 结 果 评 定； 缺陷记录缺陷编号
 * */
const config评定=[['焊缝编号','wd',78],['厚度(mm)','th',82],['检测长度(mm)','cl',120],
    ['缺陷记录缺陷编号','nm',104],['缺陷位置','po',110],['长度(mm)','l',75],['深度(mm)','d',85],['高度(mm)','h',82],
    ['缺陷类型','t',78],['评定级别','c',75],['数据文件名','f',365],] as Each_ZdSetting[];
export const Evaluation=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const breaks=[140,420,620];     //看内容调整: 更紧凑点的
        const headview=<Text variant="h5">
            检 测 结 果 评 定：
        </Text>;
        const {render}=useRepTableEditor({ref,nestMd,show,alone,redId,
            config: config评定, table:'评定表', column:3, breaks, label:'衍射时差法-检测结果 评定', headview
        });
        return  render;
} );

export const itemA检示意=['示图说明','_FILE_S示意'];
/**检测示意图
 * 支持多个图片： 每个图片单独一张纸答应的，需要附加框框和格式化的说明。 打印：也要前面强制地断开页！
 * */
export const Schematic=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd,verId,repId}:InternalItemProps,  ref
    ) => {
        const {modified,setModified,} =React.useContext(EditStorageContext) as any;
        const [getInpFilter] = useMeasureInpFilter(null, itemA检示意, );
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });

        const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
            onSure({...inp, '_FILE_S示意': upfile});
            !modified && setModified(true);
        }, [inp, modified,onSure,setModified]);
        const [uploadDom]=useUppyUpload({ repId:repId!,
            maxFile:3, onFinish, storeObj: inp?._FILE_S示意
        });

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'衍射时差法-检测示意图'} column={0}>
                检测示意图；允许多文件，多个图<br/>
                <InputLine label={`检测示意图检测部位说明：`}>
                    <BlobInputList value={inp?.示图说明 || ''} rows={5}
                                   onListChange={v => setInp({...inp, 示图说明: v || undefined}) } />
                </InputLine>
                {uploadDom}
                {children}
            </InspectRecordLayout>
        );
    } );

export const itemA衍图谱=['_FILE_S图谱', '图谱说明' ];
export const Spectrum=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd,verId,repId}:InternalItemProps,  ref
    ) => {
        const {modified,setModified,} =React.useContext(EditStorageContext) as any;
        const [getInpFilter] = useMeasureInpFilter(null, itemA衍图谱, );
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });

        const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
            onSure({...inp, '_FILE_S图谱': upfile});
            !modified && setModified(true);
        }, [inp, modified,onSure,setModified]);
        const [uploadDom]=useUppyUpload({ repId:repId!,
            maxFile:6, onFinish, storeObj: inp?._FILE_S图谱
        });
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'衍射时差法-TOFD图谱'} column={0}>
                TOFD图谱；允许多文件，每个图一张纸<br/>
                <InputLine label={`TOFD图谱-说明：`}>
                    <BlobInputList value={inp?.图谱说明 || ''} rows={5}
                                   onListChange={v => setInp({...inp, 图谱说明: v || undefined}) } />
                </InputLine>
                {uploadDom}
                {children}
            </InspectRecordLayout>
        );
} );


/*CSS:例子
    css={[
    {
        alignItems: "baseline",
        "&.InputGroup:first-of-type": {
            marginTop: 0
       }
         <div css={{
                display: 'flex',flexWrap: 'wrap',alignItems: 'baseline',
                "& > div": {
                    // width: 'unset',
                }
            }}>
                {(config通道表).map(([title,tag,width]:any,i:number) => {
                    return (
                        <React.Fragment key={i}>
                            <div key={i} css={{width,textWrap:'nowrap' }}>{title} {i===7? '': i%3===2? '┃':'╻'}</div>
                        </React.Fragment>
                    );
          } )  }   </div>
* */
